<template>
  <div style="width: 100%" class="ant-card">
    <layout-content topTitle="查询" bottomTitle="兑换专区">
    <!-- 搜索区域 -->
    <template v-slot:topCard>
      <search-view ref="searchView" @search="search" ></search-view>
    </template>
    <!-- 额外操作，在右侧 -->
    <template v-slot:extraOperation>
      <a-button class="extra-btn" type="primary" @click="handleOperationClick('add')">
        新增
      </a-button>
    </template>

    <!-- 表格区域 -->
    <template v-slot:bottomCard>
      <a-table
        ref="TableInfo"
        :columns="columns"
        rowKey="id"
        :loading="loading"
        :scroll="{ y: 400 }"
        :pagination="pagination"
        :data-source="dataSource"
      >
      <template slot="imgs" slot-scope="text">
        <a :href="text" target="_blank">
          <img class="code-img" :src="text" alt="" />
        </a>
      </template>
        <template slot="operation" slot-scope="text, record">
          <a-button  type="link" @click="handleOperationClick('edit', record)" class="icon">修改</a-button>
          <a-button  type="link"  @click="onDelete(record)" class="icon">删除</a-button>
        </template>
      </a-table>
    </template>
    </layout-content>

    <!--新增/修改-->
    <add-record
      :addOrEdit="addOrEdit"
      :key="addKey"
      :visible="addVisible"
      :initRecord="selectedRecord"
      :apiURL="apiURL"
      @close="onClose"
      @success="onAddSuccess"
    ></add-record>
  </div>
</template>

<script>
import columns from './columns';
import apiURL from './requestURL';
import searchView from './search-view';
import addRecord from './add';
import layoutContent from '@/components/tool/layout-content';

export default {
  name: "main",
  components: {searchView, addRecord, layoutContent},
  data() {
    return {
      // 添加或编辑
      addOrEdit: 0,
      // 组件渲染的key
      addKey: new Date().getTime(),
      params: {},
      columns,  // 表头字段
      apiURL, // 接口url
      // 组件的可见性
      addVisible: false,
      // 当前选中的记录
      selectedRecord: {},
      dataSource: [],
      sortedInfo: null,
      paginationInfo: null,
      pagination: {
        size: 'small',
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      },
      loading: false,
    }
  },
  created() {
    this.search();

  },
  methods: {
    // 1.查询记录
    fetch(params={}){
      this.loading = true;
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current;
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize;
        params.pageSize = this.paginationInfo.pageSize;
        params.pageNum = this.paginationInfo.current;
      } else {
        // 如果分页信息为空，则设置为默认值
        params.count = this.pagination.defaultPageSize;
        params.currentPage = this.pagination.defaultCurrent;
      }
      this.$get(apiURL.getRecords, {
        ...params
      }).then(r => {
        let data = r.data.data;
        let pagination = {...this.pagination};
        pagination.total = data.total;
        this.dataSource = data.rows;
        this.pagination = pagination;
        this.loading = false;
      }).catch(e => {
        console.error(e);
        this.loading = false;
      });
    },
    // 2.搜索
    search(params = {}) {
      this.params = params;
      let {sortedInfo} = this;
      let sortField, sortOrder;
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field;
        sortOrder = sortedInfo.order;
      }
      this.fetch({
        ...params,
        sortField: sortField,
        sortOrder: sortOrder
      });
    },
    //3. 新增/修改
    handleOperationClick(key, record = {}){
      this.addOrEdit = key === 'add' ? 0 : 1;
      record.imageList = [record.image];
      console.log(record)
      this.selectedRecord = record;
      this[`addKey`]++;
      this.addVisible = true;
    },
    //4. 删除
    onDelete(record) {
      let that = this;
      this.$confirm({
        title: '确定删除吗?',
        content: '删除将不能恢复哦！',
        centered: true,
        onOk() {
          that.$delete(apiURL.deleteRecord+ '/'+record.id).then(() => {
            that.$message.success('删除成功');
            that.search();
          });
        },
        onCancel() {}
      });
    },

    //5、修改/新增成功实践
    onAddSuccess(){
      this.addVisible = false;
      this.$message.success('操作成功');
      this.search();
    },

    //6、关闭事件
    onClose(){
      this.addVisible = false
    }
  }

}
</script>

<style lang="less" scoped>
.code-img {
  width: 50px !important;
  margin: 10px 2px;
}

.icon {
  padding: 0;
  border: none;
  color: #1890ff;
}

.card-area {
  .extra-btn {
    width: 86px;
  }
}

.search-btn {
  margin-top: 8px;
}
.code-img {
  width: 4rem !important;
}
.border-span {
  width: 2px;
  background-color: #cfd7de;
  height: 16px;
  margin-right: 2px;
  display: inline-block;
}
</style>
